﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;

using System.Security.Claims;

namespace BlazorAppWithCookieAuth.Client;
/// <summary>
/// 
/// </summary>
internal class CookieClientAuthenticationStateProvoider : AuthenticationStateProvider
{
    private static readonly Task<AuthenticationState> defaultUnauthenticatedTask = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));

    private readonly Task<AuthenticationState> authenticationStateTask = defaultUnauthenticatedTask;

    public CookieClientAuthenticationStateProvoider(PersistentComponentState state)
    {
        if (!state.TryTakeFromJson<UserInfo>(nameof(UserInfo), out var userInfo) || userInfo is null)
            return;
        Claim[] claims = [
            new Claim( ClaimTypes.Name,userInfo.UserName),
            new Claim( ClaimTypes.GivenName,userInfo.GivenName),
        ];

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie"));

        authenticationStateTask = Task.FromResult(new AuthenticationState(claimsPrincipal));
    }
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        return authenticationStateTask;
    }
}
